package org.groupg.practice;

import io.github.resilience4j.bulkhead.Bulkhead;
import io.github.resilience4j.bulkhead.BulkheadConfig;
import io.github.resilience4j.ratelimiter.RateLimiter;
import io.github.resilience4j.ratelimiter.RateLimiterConfig;
import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ConcurrencyExample {

    // 模拟耗时IO操作
    static String ioBoundOperation() throws InterruptedException {
        Thread.sleep(300); // 模拟IO延迟
        return "IO operation result";
    }

    public static void main(String[] args) throws InterruptedException {
        // 配置信号量隔离：最大并发数=2
        BulkheadConfig bulkheadConfig = BulkheadConfig.custom()
                .maxConcurrentCalls(2)
                .build();
        Bulkhead bulkhead = Bulkhead.of("myBulkhead", bulkheadConfig);

        // 配置限流：每秒1个操作
        RateLimiterConfig rateLimiterConfig = RateLimiterConfig.custom()
                .limitForPeriod(1)
                .limitRefreshPeriod(Duration.ofSeconds(1))
                .timeoutDuration(Duration.ofMillis(500))
                .build();
        RateLimiter rateLimiter = RateLimiter.of("myRateLimiter", rateLimiterConfig);

        // 组合弹性模块
        Runnable decoratedTask = () -> {
            try {
                String result = Bulkhead.decorateSupplier(
                        bulkhead,
                        RateLimiter.decorateSupplier(
                                rateLimiter,
                                () -> {
                                    try {
                                        return ioBoundOperation();
                                    } catch (InterruptedException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                        )
                ).get();

                System.out.println(Thread.currentThread().getName() + ": " + result);
            } catch (Exception e) {
                System.err.println(Thread.currentThread().getName() + " failed: " + e.getMessage());
            }
        };

        // 创建10个线程模拟并发请求
        ExecutorService executor = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            executor.submit(decoratedTask);
        }

        // 关闭线程池
        executor.shutdown();
        executor.awaitTermination(5, TimeUnit.SECONDS);
    }
}